import React, { useRef, useState, useMemo } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { connect, history } from 'umi';
import { VersionManageContext } from '../common/UpdateContext';
import { useUpdateReducer } from '../common/UpdateReducer';
import { VersionManageAPI } from '../common/type';
import { SchemaManage } from '@/components/SchemaComponent';
import { getKeyRouter, downloadTemplate } from '@/utils';
import {
  getVersionManageTabSwitch,
  getVersionManageTabColumns,
} from '../mconfig';
import { message } from 'antd';
import { VersionManageService, applyService } from '../services';
const VersionManageView: React.FC<VersionManageAPI.IVersionManageView> = ({
  curRes,
}) => {
  const { dispatch } = useUpdateReducer();

  const schemaManageRef: any = useRef();

  /** 获取管理页面上下文内容 */
  const {
    loading,
    pagination,
    searchList,
    data,
    refreshRequest,
    manageTableParams,
  } = VersionManageService(curRes);

  /**
   * 提交审核modal
   */
  // const [checkModal, setCheckModal] = useState<boolean>(false);

  /**
   * 作废modal
   */
  // const [cancelModal, setCancelModal] = useState<boolean>(false);

  /**
   * 保存选中数据
   */
  const [checkRowObj, setCheckRowObj] = useState<any>();

  /** 表格头部切换方法 */
  const switchList: VersionManageAPI.IVersionSwitchList[] = useMemo(() => {
    const switchArr: Record<string, any>[] = getVersionManageTabSwitch(curRes);
    return switchArr;
  }, [curRes]);

  /** 头部Tab切换 */
  const onSwitch = (
    key: string | undefined | number,
    searchValues: any,
    params: any,
  ) => {
    if (key) {
      refreshRequest({ ...params, ...searchValues, key });
    }
  };

  /** 点击搜索重置按钮 */
  const onReset = (requestParams: any) => {
    let keyValue = manageTableParams?.key;
    requestParams = {
      ...requestParams,
      key: keyValue,
    };
    refreshRequest(requestParams);
  };

  /** 点击搜索提交按钮 */
  const onSearch = (
    requestParams: VersionManageAPI.IVersionTableRequestType,
  ) => {
    requestParams = {
      ...requestParams,
      ...manageTableParams,
    };
    refreshRequest(requestParams);
  };

  /** 点击分页操作 */
  const onPageChange = (current: any, pageSize: any, params: any) => {
    let keyValue = manageTableParams?.key;
    params = {
      ...params,
      key: keyValue,
      current: current,
      pageSize: pageSize,
    };
    refreshRequest(params);
  };

  /**
   * 申请接口回调
   * @param res
   */
  const applyCallBack = (res: any) => {
    if (res && res?.msgFlag) {
      // message.success(res?.msg);
      reloadManage();
    } else {
      message.error(res?.msg);
    }
  };

  /**
   * 引入申请接口
   */
  const { applyIssueRun, applyIssueLoading, applyIssueData } = applyService(applyCallBack);

  /** 管理页面头部操作集合 */
  /** 跳转到新增版本 */
  const getSearchOperateFuncs: VersionManageAPI.IHeaderActionType =
    useMemo(() => {
      return [
        {
          title: '添加',
          visible: curRes?.['/versionController/add'] ?? true,
          type: 'primary',
          icon: <PlusOutlined />,
          onClick: () => {
            history.push({
              pathname: `/versionController/add/:${getKeyRouter()}${getKeyRouter()}`,
            });
          },
        },
      ];
    }, [curRes]);

  /** 数据表格操作集合 */
  const getTableOperateFuncs: VersionManageAPI.IVersionTableActionType = {
    /**编辑 */
    onEdit: (record) => {
      history.push({
        pathname: `/versionController/edit/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          id: record?.id,
        },
      });
    },

    /**查看 */
    onView: (record) => {
      history.push({
        pathname: `/versionController/getVersionByID/{id}/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          id: record?.id,
        },
      });
    },

    /**提交审核 */
    // onApply: (record) => {
    //   let params = {
    //     msysVersion: {
    //       id: record?.id,
    //       versionNum: record?.versionNum,
    //     },
    //   };
    //   applyIssueRun(params);
    // },

    /**作废 */
    // onCancel: (record) => {
    //   setCheckRowObj(record);
    //   setCancelModal(true);
    // },

    /**办理审核 */
    goToCheck: (record) => {
      history.push({
        pathname: `/versionController/getVersionByID/{id}/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          id: record?.id,
        },
      });
    },

    /**下载 */
    onDownload: (record) => {
      let arr = [];
      arr = record?.versionUrl?.split('/');
      let attachList = {
        attachName: arr[arr.length - 1],
        attachUrl: record?.versionUrl,
      };
      message.success('下载中，请稍后...');
      downloadTemplate(
        '/versionController/downloadFile',
        attachList?.attachName,
        attachList?.attachUrl,
        () => { },
      );
    },
  };

  /** 获取数据表格数据列 */
  const getTableColumns: Record<string, any>[] = useMemo(() => {
    let visibleFlag = {
      isPublic: false, //版本状态
      // state: false,//审核状态
      signTime: false, //发布时间
      applyTime: false, //申请时间
      applyerName: false, //申请人
      applyPositionName: false, //申请岗位
      applyDepartmentName: false, //申请部门
      applyCompanyName: false, //申请公司
    };
    if (manageTableParams?.key == 'MyVersionManageTab') {
      visibleFlag.isPublic = true;
      // visibleFlag.state = true;
      visibleFlag.signTime = true;
    } else if (manageTableParams?.key == 'MyVersionCheckTab') {
      visibleFlag.isPublic = false;
      // visibleFlag.state = false;
      visibleFlag.applyTime = true;
      visibleFlag.applyerName = true;
      visibleFlag.applyPositionName = true;
      visibleFlag.applyDepartmentName = true;
      visibleFlag.applyCompanyName = true;
    }
    return getVersionManageTabColumns(
      curRes,
      getTableOperateFuncs,
      visibleFlag,
    );
  }, [curRes, manageTableParams?.key]);

  /**
   * 刷新管理页
   */
  const reloadManage = () => {
    refreshRequest(manageTableParams);
  };

  return (
    <VersionManageContext.Provider
      value={{
        curRes, //权限
        dispatch, //派发
      }}
    >
      <SchemaManage
        ref={schemaManageRef}
        searchProps={{
          switchList,
          searchList,
          onSwitch,
          onReset,
          onSearch,
        }}
        actionList={getSearchOperateFuncs}
        tableProps={{
          columns: getTableColumns,
          dataSource: data?.rows,
          loading: loading,
          pagination: pagination as any,
          rowKey: 'id',
          onPageChange: onPageChange,
        }}
      />
      {/* 发起审核 */}
      {/* {checkModal && (
        <VersionCheckModal
          onClose={() => {
            setCheckModal(false);
          }}
          isShowModal={checkModal}
          checkRows={checkRowObj}
          reloadVersion={() => {
            reloadManage();
          }}
        />
      )} */}
      {/* 作废 */}
      {/* {cancelModal && (
        <VersionCancelModal
          onClose={() => {
            setCancelModal(false);
          }}
          isShowModal={cancelModal}
          checkRows={checkRowObj}
          reloadVersion={() => {
            reloadManage();
          }}
        />
      )} */}
    </VersionManageContext.Provider>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(VersionManageView);
